/*
 * @Author: csh
 * @Date: 2022-07-27
 * @LastEditors: BigFlower
 * @LastEditTime: 2022-08-25 22:12:14
 * @Description: file content
 * @FilePath: \wochat-vue3-ts-pinia\src\store\contact.ts
 */

import { defineStore, acceptHMRUpdate } from 'pinia';
import contactService from '@/service/chat/contactService';
import { useChatMessageStore } from './chatMessage';
import { Contact } from '@/service/entity/Contact';
import { guid } from '@/common/random';
import { ref } from 'vue';

export const useContactStore = defineStore('contactStore', ()=>{
  
    const contacts = ref<Contact[]>([]);
    const currentContact = ref<Contact>(new Contact(guid()));

    function getContact(userId: string) {
      return contacts.value.find((item:Contact) => item.id === userId);
    }

    const loadContacts = ()=> {
      contacts.value = contactService.loadContacts();
    }
    const changeCurrentContact = (userId: string) =>{
      console.log('changeCurrentContact userId', userId);
      currentContact.value = contacts.value.find((item:Contact) => item.id === userId) || new Contact(guid());
      console.log('changeCurrentContact currentContact', currentContact);
      // 联系人改变，窗口显示的消息内容也改变
      const msgStor = useChatMessageStore();
      msgStor.loadMessage(userId);
    }
    return {contacts, currentContact, loadContacts, changeCurrentContact}
});

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useContactStore, import.meta.hot));
}
